package com.itttq.kb.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.itttq.kb.model.po.TopicPo;
import com.itttq.kb.model.po.TopicReplyPo;
import com.itttq.kb.model.po.UserPo;
import com.itttq.kb.model.to.PageParamTo;
import com.itttq.kb.model.to.ResultDataTo;
import com.itttq.kb.model.to.ResultTo;
import com.itttq.kb.service.TopicReplyService;
import com.itttq.kb.service.TopicService;
import com.itttq.kb.utils.Constants;

@RestController
@RequestMapping("topic")
public class TopicController extends GenericController {
	private static final long serialVersionUID = -58683467017349714L;
	@Autowired
	private TopicService topicService;
	@Autowired
	private TopicReplyService topicReplyService;
	@Autowired
	private CommonController commonController;
	/**
	 * 首页
	 */
	@RequestMapping(value={"/index.html",""})
	public ModelAndView topicIndex(String title, HttpServletRequest request) {
		return topicIndex(null, title, request);
	}
	/**
	 * 首页给你
	 * 
	 * @param catId	分类ID，不传则获取全部
	 * @param title	主题标题，模糊查询。为空查询全部
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("/{catId}/index.html")
	public ModelAndView topicIndex(@PathVariable("catId") Integer catId, String title, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/topic/index");
		mv = getUserAndTopic(catId, mv, request);
		mv.addObject("catId", catId);
		
		// 获取最新帖子
		TopicPo topic = new TopicPo();
		topic.setCategoryId(catId);
		topic.setTitle(title);
		PageParamTo ppt = this.getPageParam(request);
		this.getPageMv("latestTopics", mv, topicService.getTopics(topic, ppt), topicService.getTopicCount(topic), ppt);
		// 获取置顶帖子
		topic.setIsTop(Constants.STATUTS_OPEN);
		mv.addObject("topTopics", topicService.getTopics(topic, this.getPageParam(10)));
		return mv;
	}
	
	@RequestMapping("save")
	public ResultTo saveTopic(TopicPo topic, HttpServletRequest request) {
		ResultTo rt = new ResultTo(ResultTo.FAIL);
		rt.setMsg("保存主题失败！");
		try {
			// 获取session
			UserPo user = this.getUserBySession(request);
			if(null != user) topic.setUpdaterId(user.getId());
			if(null == topic.getId() || topic.getId() < 1) {
				if(null != user) {
					topic.setCreatorId(user.getId());
					topic.setCreatorName(user.getName());
					topic.setCreatorAvatar(user.getAvatar());
				}
				topicService.addTopic(topic);
			} else {
				topicService.updateTopic(topic);
			}
			rt.setCode(ResultTo.SUCCESS);
			rt.setMsg("保存主题成功！");
		} catch(Exception e) {
			// TODO 日志记录
		}
		return rt;
	}
	
	@RequestMapping("topics")
	public ModelAndView getTopics(TopicPo topic, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/topic/topics");
		PageParamTo ppt = this.getPageParam(request);
		this.getPageMv("topics", mv, topicService.getTopics(topic, ppt), topicService.getTopicCount(topic), ppt);
		mv.addObject("topic", topic);
		return mv;
	}
	/**
	 * 根据ID获取主题详细信息
	 * 
	 * @param id
	 * @param request
	 * @return
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("detail/{id}.html")
	public ModelAndView getTopicDetail(@PathVariable("id") Integer id, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/topic/detail");
		TopicPo topic = topicService.getTopic(id);
		mv.addObject("catId", topic.getCategoryId());
		mv.addObject("topic", topic);
		mv = getUserAndTopic(topic == null ? null : topic.getCategoryId(), mv, request);
		// 获取回复，暂未分页
		TopicReplyPo topicReply = new TopicReplyPo();
		topicReply.setTopicId(id+0l); // +0l是偷懒，简单转换为Long
		mv.addObject("replies", topicReplyService.getTopicReplys(id, this.getPageParam(5)));
		try {
			// 更新阅读数，此处有BUG，应该是+1的方式来做
			TopicPo tp = new TopicPo();
			tp.setId(id);
			tp.setNumberRead((null == topic.getNumberRead() ? 0 : topic.getNumberRead()) + 1);
			topicService.updateTopic(tp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("edit/{id}.html")
	public ModelAndView editTopic(@PathVariable("id") Integer id, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/topic/add");
		mv.addObject("topic", topicService.getTopic(id));
		return mv;
	}
	
	/**
	 * 上传图片
	 * 
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("/uploadImg")
	public ResultDataTo<Map<String, String>> uploadImg(Integer dirType, MultipartFile file, HttpServletRequest request) {
		ResultDataTo<Map<String, String>> rdt = new ResultDataTo<Map<String, String>>(ResultTo.FAIL);
		try {
			ResultTo rt = commonController.uploadImage(dirType, file);
			if(rt.getCode() == ResultTo.SUCCESS) {
				rdt.setCode(ResultTo.SUCCESS_FILE);
				rdt.setMsg("上传图片成功！");
				Map<String, String> data = new HashMap<String, String>();
				data.put("src", rt.getMsg());
				rdt.setData(data);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rdt;
	}
}
